from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render
from django.db import connection
import requests
import json
from pymysql.converters import escape_string
import os
import django
from django.http import HttpResponseRedirect
from django.urls import reverse


class File_object:
    def __init__(self, file_name, title, content, score):
        self.file_name = file_name
        self.title = title
        self.content = content
        self.score = score


class words:
    def __init__(self, eng, chi):
        self.eng = eng
        self.chi = chi

# def index(request):
#     print("访问首页 index.html  ")
#     api_request = requests.get("http://www.baidu.com")
#     resp = {
#         'title':'    title 标题  >>>  ',
#         "key": api_request.content
#     }
#     obj_0 = File_object("file_00", "Docker 安装 Java JDK 8" , "Docker 的旧版本被称为 docker，docker.io 或 docker-engine 。如果已安装，请卸载它们：" , 56)
#     obj_1 = File_object("file_11", "JavaScript 教程" , "JavaScript 是 Web 的编程语言。所有现代的 HTML 页面都可以使用 JavaScript。" , 12)
#     print(obj_0.title)
#     return render(request,'index/inde.html', {'data': json.dumps(obj=obj_0.__dict__,ensure_ascii=False)})


@csrf_exempt
def ajax_post_test(request):
    if request.method == 'POST':
        print("ajax test =============================")
        data = json.loads(request.body)
        print(data)
        print(data['word'])
        word = data['word']
        sql = "SELECT english,chinese FROM tb_word WHERE english  LIKE '%s'" % (escape_string(word))
        print(sql)
        listtt=[]
        with connection.cursor() as cursor:
            cursor.execute(sql)
            result = cursor.fetchall()
            for ii in result:
                eng = ii[0]
                chi = ii[1]
                new_word = words(eng, chi)
                print(new_word)
                print(new_word)
                listtt.append(new_word.__dict__)

        dict = {'aaa': 'aaaaaa', 'bbbbbbb': 'bbbbbbbbbbbb'}
        return HttpResponse(json.dumps(listtt), content_type="application/json")
    else:
        return HttpResponse("哈哈哈哈哈哈哈哈哈", content_type="application/json")


@csrf_exempt
def ajax_get_test(request):
    if request.method == 'GET':
        user_id = request.GET.get('id', None)
        user_name = request.GET.get('name', None)
        print(user_id)
        print(user_name)
        return HttpResponse("哈哈哈哈哈哈哈哈哈", content_type="application/json")
    else:
        return HttpResponse("哈哈哈哈哈哈哈哈哈", content_type="application/json")
